package com.linkstec.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class ChatGPTUtil {

    public static void main(String[] args) {
        HttpPost httpPost = new HttpPost(
                "https://cog-fen5iye5av5vg.openai.azure.com/openai/deployments/chat/chat/completions?api-version=2023-03-15-preview");
        httpPost.setHeader("Content-type", "application/json;charset=UTF-8");
        httpPost.setHeader("api-key", "d85aadf25c664235a735ffe470f506c3");
        Map<String, Object> requestMap = new HashMap<String, Object>();
        requestMap.put("temperature", 0.7);
        requestMap.put("max_tokens", 2048);
        requestMap.put("top_p", 0.95);
        requestMap.put("frequency_penalty", 0);
        requestMap.put("presence_penalty", 0);
        requestMap.put("stop", null);
        List<Map<String, Object>> messages = new ArrayList<Map<String, Object>>();
        Map<String, Object> message = new HashMap<String, Object>();
        message.put("role", "user");
        message.put("content", "hello");
        messages.add(message);
        requestMap.put("messages", messages);

        String result = null;
        try {
            String requestBody = JSON.toJSONString(requestMap);

            System.out.println("请求体：" + requestBody);
            httpPost.setEntity(new StringEntity(requestBody));
            result = HttpClientUtil.post(httpPost);
            System.out.println("调用chatGPT,返回值" + result);
            if (StringUtils.isNotEmpty(result)) {
                JSONObject jSONObject = JSON.parseObject(result);
                String messageContent = jSONObject.getJSONArray("choices").getJSONObject(0).getJSONObject("message")
                        .getString("content");
                System.out.println("messageContent值：" + messageContent);
            }
        } catch (IOException e) {
            System.out.println(ExceptionUtils.getStackTrace(e));
        }
    }
}
